import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex);

const store = new Vuex.Store({
	modules: {},

	state: {
		carts: [{
				id: 1,
				title: '腾讯极光盒子4智能网络电视机顶盒6K千兆网络机顶盒4K高分辨率',
				titleImage: 'https://cdn-we-retail.ym.tencent.com/tsr/goods/nz-09a.png?imageMogr2/thumbnail/645x645/quality/70/strip/format/webp',
				quantity: 1,
				checked: true,
				price: 99.98,
				company: '华为旗舰店',
				companyId: 1
			},
			{
				id: 2,
				title: '腾讯极光盒子4智能网络电视机顶盒6K千兆网络机顶盒4K高分辨率',
				titleImage: 'https://cdn-we-retail.ym.tencent.com/tsr/goods/nz-09a.png?imageMogr2/thumbnail/645x645/quality/70/strip/format/webp',
				quantity: 1,
				checked: true,
				price: 99.98,
				company: '华为旗舰店',
				companyId: 1
			}
		]
	},
	mutations: {
		modifyCartItem(state, value) {
			for (let s of state.carts) {
				if (s.id === value.id) {
					s.checked = value.checked
					s.quantity = value.quantity
					return
				}
			}
		},
		modifyAllCarts(state, value) {
			for (let s of state.carts) {
				s.checked = value
			}
		},
		modifyCartGroup(state, {
			id,
			value
		}) {
			for (let s of state.carts) {
				if (s.companyId === id) {
					s.checked = value
				}
			}
		}
	},
	getters: {
		cartsGroup(state) {
			let x = {}
			state.carts.forEach(it => {
				if (!x[it.companyId]) {
					x[it.companyId] = []
				}
				x[it.companyId].push(it)
			})
			let res = []
			for (let c in x) {
				let groupChecked = x[c].every(it => it.checked)
				let name = x[c][0].company
				let id = x[c][0].companyId
				res.push({
					id,
					name,
					checked: groupChecked,
					products: x[c]
				})
			}
			return res
		},
		allCartChecked(state){
			return state.carts.every(it=> it.checked)
		},
		allCartNotChecked(state){
			return state.carts.every(it => !it.checked)
		},
		cartsAmount(state) {
			return state.carts
				.filter(it => it.checked)
				.map(it => it.price * it.quantity)
				.reduce((i1, i2) => i1 + i2, 0)
		}
	},
	actions: {

	}
})

export default store